from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time


def load_game_data(driver):
    # 查找所有游戏项
    games = driver.find_elements(By.XPATH, "//html/body/div[4]/div[2]/div[1]/ul/li")
    for game in games:
        try:
            name = game.find_element(By.XPATH, ".//div[1]/div[2]/div[1]").text
            ename = game.find_element(By.XPATH, ".//div[1]/div[2]/div[2]").text
            gclass = game.find_element(By.XPATH, ".//div[1]/div[2]/div[3]").text
            uscore = game.find_element(By.XPATH, ".//div[2]").text
            pscore = game.find_element(By.XPATH, ".//div[3]").text

            # 打印游戏信息
            print(name + " " + ename + " " + gclass + " " + uscore + " " + pscore)
        except Exception as e:
            print(f"提取游戏信息时发生错误: {e}")


def load_more_content(driver):
    while True:
        # 等待“下一页”按钮出现并且可点击
        try:
            next_button = WebDriverWait(driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, "span#pe100_page_phblist a.nexe"))
            )

            # 使用 JavaScript 点击“下一页”
            driver.execute_script("arguments[0].click();", next_button)
            time.sleep(2)  # 等待新内容加载
            load_game_data(driver)  # 提取当前页游戏数据
        except Exception as e:
            print(f"发生错误：{e}")
            break


if __name__ == '__main__':
    # 创建并配置 WebDriver
    qd = webdriver.Chrome()
    qd.get("https://www.gamersky.com/review/top/")

    try:
        load_game_data(qd)  # 提取第一页游戏数据
        load_more_content(qd)  # 加载更多内容并提取数据
    except Exception as e:
        print(f"总体运行中发生错误：{e}")
    finally:
        qd.quit()  # 确保结束时关闭浏览器